from PySide6 import QtWidgets, QtGui, QtCore
from .nodegraph import FlowCanvas
from . import nodegraph
import os

class DraggableTreeWidget(QtWidgets.QTreeWidget):

    def __init__(self, parent = None):
        super(DraggableTreeWidget, self).__init__(parent)
        self.setDragDropMode(QtWidgets.QTreeWidget.DragOnly)

    def startDrag(self, supportedActions):

        items = self.selectedItems()
        if not items:
            return
        item = items[0]
        drag = QtGui.QDrag(self)
        mimedata = QtCore.QMimeData()

        itemdata = item.text(1)
        mimedata.setText(itemdata)
        drag.setMimeData(mimedata)

        pixmap = self.grab(self.visualItemRect(item))
        drag.setPixmap(pixmap)
        drag.setHotSpot(pixmap.rect().center())

        drag.exec_(QtCore.Qt.CopyAction)

        return super().startDrag(supportedActions)

class EditorMainWindow(QtWidgets.QMainWindow):
    
    def __init__(self):
        super(EditorMainWindow, self).__init__()
        self._tabwidget = QtWidgets.QTabWidget()
        self._tabwidget.setTabsClosable(True)

        w = QtWidgets.QWidget()
        w.setObjectName("CentralMW")
        w.setLayout(QtWidgets.QVBoxLayout())
        w.layout().setContentsMargins(1, 0, 0, 0)

        self._centralmw = QtWidgets.QMainWindow()
        self._centralmw.setCentralWidget(self._tabwidget)

        w.layout().addWidget(self._centralmw)

        self.setCentralWidget(w)
        w.setStyleSheet("""
QWidget#CentralMW{
    border-left: 1px solid #393939;
}
""")
        self._leftdockwidget = QtWidgets.QDockWidget()
        self._leftdockwidget.setAllowedAreas(QtCore.Qt.DockWidgetArea.LeftDockWidgetArea)
        self._leftdockwidget.setWindowTitle("Flows")
        self._leftdockwidget.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable)
        self.addDockWidget(QtCore.Qt.DockWidgetArea.LeftDockWidgetArea, self._leftdockwidget)

        self._actionsdockwidget = QtWidgets.QDockWidget()
        self._actionsdockwidget.setAllowedAreas(QtCore.Qt.DockWidgetArea.LeftDockWidgetArea)
        self._actionsdockwidget.setWindowTitle("Actions")
        self._actionsdockwidget.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable)
        self.splitDockWidget(self._leftdockwidget, self._actionsdockwidget, QtCore.Qt.Vertical)

        self._bottomdockwidget = QtWidgets.QDockWidget()
        self._bottomdockwidget.setAllowedAreas(QtCore.Qt.DockWidgetArea.BottomDockWidgetArea)
        self._bottomdockwidget.setWindowTitle("Console")
        self._centralmw.addDockWidget(QtCore.Qt.DockWidgetArea.BottomDockWidgetArea, self._bottomdockwidget)
        self._bottomdockwidget.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable | QtWidgets.QDockWidget.DockWidgetClosable)

        self._flowsTreeWidget = QtWidgets.QTreeWidget()
        self._flowsTreeWidget.setHeaderHidden(True)
        self._leftdockwidget.setWidget(self._flowsTreeWidget)

        self._actionsTreeWidget = DraggableTreeWidget()
        self._actionsTreeWidget.setHeaderHidden(True)
        self._actionsTreeWidget.setColumnWidth(0, 200)
        self._actionsdockwidget.setWidget(self._actionsTreeWidget)
        self._internalactionItem = QtWidgets.QTreeWidgetItem()
        self._internalactionItem.setText(0, "InternalActions")
        self._customactionsItem = QtWidgets.QTreeWidgetItem()
        self._customactionsItem.setText(0, "CustomActions")
        self._actionsTreeWidget.addTopLevelItem(self._internalactionItem)
        self._actionsTreeWidget.addTopLevelItem(self._customactionsItem)

        self.InitConfig()
        self.InitFlowTreeWidget()
        self.InitActionTreeWidget()
        self.RefreshAllFlows()
        self.InitMenu()

    def InitMenu(self):
        pass

    def InitConfig(self):
        nodegraph.InitConfig()
        self._canvas = { }

    def InitFlowTreeWidget(self):
        self._flowsTreeWidget.itemDoubleClicked.connect(self.onDoubleClickFlowItem)

    def InitActionTreeWidget(self):
        from autoflow import actionmanager, flowmanager
        for uid, actobj in actionmanager.g_ActMgr._actions.items():
            item = QtWidgets.QTreeWidgetItem()#actobj.GetName())
            item.setText(0, actobj.GetName())
            item.setText(1, uid)
            self._customactionsItem.addChild(item)
        for nn, ncls in flowmanager.g_NodeCls.items():
            item = QtWidgets.QTreeWidgetItem()#actobj.GetName())
            item.setText(0, ncls._name)
            item.setText(1, nn)
            self._internalactionItem.addChild(item)

    def GetCurrentCanvas(self):
        curwidget = self._tabwidget.currentWidget()
        if not curwidget:
            return
        filepath = curwidget.filepath
        if filepath not in self._canvas:
            return
        canvas = self._canvas[filepath]
        return canvas
    
    def GetCurrentCanvasTabWidget(self):
        curwidget = self._tabwidget.currentWidget()
        if not curwidget:
            return None
        return curwidget

    def RefreshAllFlows(self):
        self._flowsTreeWidget.clear()
        DebugPrint(nodegraph.autoflow.flowmanager.g_FlowManager._flows.items())
        for uid, flowobj in nodegraph.autoflow.flowmanager.g_FlowManager._flows.items():
            DebugPrint(uid, flowobj)
            item = QtWidgets.QTreeWidgetItem()
            item.setText(0, flowobj._name)
            item.setText(1, uid)
            self._flowsTreeWidget.addTopLevelItem(item)

    def EditFlows(self, filepath: str):
        filepath = os.path.abspath(filepath)
        w = self._canvas.get(filepath, None)
        if not w:
            canvas = FlowCanvas()
            canvas.loadFlowConfig(filepath)
            self._canvas[filepath] = canvas
            self._tabwidget.addTab(canvas.widget(), canvas._name)
            w = canvas.widget()
            w.filepath = filepath
        else:
            w = w.widget()
        self._tabwidget.setCurrentWidget(w)

        self._canvas[filepath]._graph._viewer.data_dropped.connect(self.droppedItem)

    def droppedItem(self, mimedata, pos):
        DebugPrint(mimedata, mimedata.text(), pos)
        canvas = self.GetCurrentCanvas()
        if not canvas:
            return
        if "N_" == mimedata.text()[:2]:
            acttype = mimedata.text()
            actid = ""
        else:
            acttype = "ACTION"
            actid = mimedata.text()
        canvas.addActionToCanvas(actid, pos.x(), pos.y(), acttype)

    def onDoubleClickFlowItem(self, item, column):
        name = item.text(0)
        uid = item.text(1)
        DebugPrint("double click: ", name, uid)
        flowsdir = os.path.join(os.getcwd(), "flows")
        filepath = os.path.join(flowsdir, f"{uid}.json")
        self.EditFlows(filepath)

    def saveCurrentFlow(self):
        curwidget = self._tabwidget.currentWidget()
        if not curwidget:
            return
        filepath = curwidget.filepath
        if filepath not in self._canvas:
            return
        canvas = self._canvas[filepath]
        canvas.Save()

